const fastify = require('fastify')({
    logger: true,
    bodyLimit: 10 * 1024 * 1024
});
const {
    audioToWavBuffer,
    audioToMp3Buffer,
    tts,
    recognizer
} = require('./utils');

fastify.register(require('@fastify/multipart'), {
    limits: {
        fieldSize: 10 * 1024 * 1024 // 10MB
    }
});

// 支持 JSON 数据传输
fastify.register(require('@fastify/formbody'));


// 声明 TTS 接口
fastify.post('/tts', async (request, reply) => {
    try {
        const {
            text,
            type = 'wav',
            sid = 0,
            speed = 1
        } = request.body;
        console.log(request.body)
        if (!text || typeof text !== 'string' || text.trim().length === 0) {
            throw new Error('无效的输入文本');
        }

        // 语音合成
        const audio = tts.generate({ text, sid, speed });

        if (type === 'wav') {
            reply
                .header('Content-Type', 'audio/wav')
                .header('Content-Disposition', 'inline; filename="tts.wav"')
                .send(audioToWavBuffer(audio));
        } else if (type === 'mp3') {
            reply
                .header('Content-Type', 'audio/mpeg')
                .header('Content-Disposition', 'inline; filename="tts.mp3"')
                .send(audioToMp3Buffer(audio));
        } else {
            throw Error('unknown audio format');
        }
    } catch (error) {
        console.error('[TTS]处理失败:', error);
        reply
            .code(500)
            .send({ success: false, error: error.message });
    }
});


// 修改 ASR 接口以接收文件上传
fastify.post('/asr', async (request, reply) => {
    try {
        const data = await request.file();
        if (!data) {
            throw new Error('no audio file received');
        }

        // 使用流式处理
        const chunks = [];
        let totalSize = 0;

        for await (const chunk of data.file) {
            chunks.push(chunk);
            totalSize += chunk.length;
            // 如果文件太大，提前终止
            if (totalSize > 10 * 1024 * 1024) { // 10MB 限制
                throw new Error('文件太大');
            }
        }

        const buffer = Buffer.concat(chunks);

        // 解析 WAV 文件头
        const sampleRate = buffer.readUInt32LE(24);
        const audioData = buffer.slice(44); // 跳过 44 字节的 WAV 头

        // 转换为 Float32Array
        const float32Samples = new Float32Array(audioData.length / 2);
        for (let i = 0; i < float32Samples.length; i++) {
            float32Samples[i] = audioData.readInt16LE(i * 2) / 32768.0;
        }

        // 进行语音识别
        const stream = recognizer.createStream();
        stream.acceptWaveform(sampleRate, float32Samples);

        recognizer.decode(stream);
        const result = recognizer.getResult(stream);
        reply.send({
            success: true,
            text: result
        });
    } catch (error) {
        console.error('[ASR]处理失败:', error);
        reply
            .code(500)
            .send({ success: false, error: error.message });
    }
});

// 启动服务
const start = async () => {
    try {
        await fastify.listen({ port: 8000, host: '0.0.0.0' });
    } catch (err) {
        fastify.log.error(err);
        process.exit(1);
    }
};

start();
